package com.zwt.utils.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

/**
 * Created by hello on 2017/11/6.
 */
public class SpringContextUtil {
    /**
     * spring的上下文
     */
    private static ApplicationContext ctx;

    /**
     * 根据指定bean名称，获取对应的实例对象
     * @param name bean的名称
     * @return 对应bean的实例对象
     */
    public static Object getBean(String name) {
        if (ctx == null) {
            throw new RuntimeException("spring 上下文对象未初始化，无法完成bean的查找！");
        }
        return ctx.getBean(name);
    }
    /**
     * @return the ctx
     */
    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    /**
     * @param ctx the ctx to set
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;
    }

    //============================零元购相关============================//

    public static <T> T getBean1(String beanName) {
        //ServletContext servletContext = request.getSession().getServletContext();
        //ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if (StringUtils.isEmpty(beanName)) {
            return null;
        }
        char c = beanName.charAt(0);
        char c1 = beanName.charAt(1);
        if (c >= 'A' && c <= 'Z' && !(c1 >= 'A' && c1 <= 'Z')) {
            beanName = String.valueOf((char) (c + 32)) + beanName.substring(1);
        }
        T t = null;
        try {
            t = (T) ctx.getBean(beanName);
        } catch (Exception e) {
            t = (T) ctx.getBean(beanName + "Impl");
        }
        return t;
    }

    public static <T> T getBean1(Class clazz) {
        return (T) getBean1(clazz.getSimpleName());
    }
}
